package com.pine.common.trigger;

import com.pine.common.redis.lock.RedisLock;

import java.util.Objects;

/**
 * 触发器工具类
 *
 * @author pine manage
 * @since 2024-08-09
 */
public class TriggerUtil {

    /**
     * 触发器执行
     *
     * @param triggerContext 触发器上下文
     * @return 触发器响应
     */
    public static <TriggerRequest, TriggerResponse> TriggerResponse trigger(TriggerContext<TriggerRequest> triggerContext) {
        AbstractTriggerTemplate<TriggerRequest, TriggerResponse> trigger = TriggerFactory.getTrigger(triggerContext.getTriggerType());
        Objects.requireNonNull(trigger, () -> "未找到" + triggerContext.getTriggerType() + "触发器");
        return trigger.execute(triggerContext);
    }


    /**
     * 触发器执行，加锁限流<br>
     * <b>此处注意：上锁后不手动解锁，等待过期时间自动解锁</b>
     *
     * @param triggerContext 触发器上下文
     * @param expire         锁过期时间
     * @param acquireTimeout 获取锁超时时间
     * @return 触发器响应
     */
    public static <TriggerRequest, TriggerResponse> TriggerResponse triggerWithLock(TriggerContext<TriggerRequest> triggerContext, Long expire, Long acquireTimeout) {
        // 获取锁&限流
        RedisLock.lockAndLimitStream(triggerContext, expire, acquireTimeout);
        // 获取锁成功，触发器执行
        return trigger(triggerContext);
    }

    /**
     * 触发器执行，加锁限流<br>
     * <b>此处注意：上锁后不手动解锁，等待过期时间自动解锁</b>
     *
     * @param triggerContext 触发器上下文
     * @return 触发器响应
     */
    public static <TriggerRequest, TriggerResponse> TriggerResponse triggerWithLock(TriggerContext<TriggerRequest> triggerContext) {
        return triggerWithLock(triggerContext, null, null);
    }
}
